<template>
  <div v-loading="loading" :element-loading-text="loadingText" style="min-height: 400px;">
    <div ref="chartRef" style="width: 100%; height: 70vh;"></div>
    <el-empty v-if="!loading && !hasData" :description="emptyText" />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick, watch } from 'vue';
import * as echarts from 'echarts/core';
import { TreeChart } from 'echarts/charts';
import { TooltipComponent, GridComponent } from 'echarts/components';
import { CanvasRenderer } from 'echarts/renderers';
import { getRootsApi, getFullTreeApi } from '@/api/genealogy'; //
import type { GenealogyNodeDTO } from '@/types/api'; //
import { ElMessage } from 'element-plus';

echarts.use([TooltipComponent, TreeChart, CanvasRenderer, GridComponent]);

const props = defineProps<{ treeId: number }>();
const emit = defineEmits(['node-click']);

const chartRef = ref<HTMLElement>();
let myChart: echarts.ECharts | null = null;
const loading = ref(true);
const loadingText = ref("正在加载家谱数据...");
const hasData = ref(false);
const emptyText = ref("此家谱没有可用于生成图表的根人物。");

const initChart = (data: GenealogyNodeDTO) => {
  if (!chartRef.value) return;
  if(myChart) {
    myChart.dispose();
  }
  myChart = echarts.init(chartRef.value);

  myChart.on('click', (params: any) => {
    if (params.componentType === 'series' && params.seriesType === 'tree' && params.data) {
      const nodeData = params.data as GenealogyNodeDTO;
      if (nodeData.personId) { //
        emit('node-click', nodeData.personId); //
      }
    }
  });

  const option = {
    tooltip: {
      trigger: 'item',
      triggerOn: 'mousemove',
      formatter: (params: any) => {
          const node = params.data as GenealogyNodeDTO;
          if (!node.person) return ''; //
          let text = `<strong>${node.person.name}</strong><br/>`; //
          text += `性别: ${node.person.gender === 'M' ? '男' : (node.person.gender === 'F' ? '女' : '其他')}<br/>`; //
          if(node.person.birthDate) text += `出生: ${node.person.birthDate}<br/>`; //
          if(node.person.deathDate) text += `逝世: ${node.person.deathDate}<br/>`; //

          // 【修正】在 tooltip 中显示配偶信息
          if (node.spouses && node.spouses.length > 0) { //
              text += `配偶: ${node.spouses.map(s => s.name).join(', ')}<br/>`; //
          }
          return text;
      }
    },
    series: [
      {
        type: 'tree',
        data: [data],
        top: '5%',
        left: '10%',
        bottom: '5%',
        right: '20%',
        symbol: 'circle',
        symbolSize: 15,
        orient: 'TB',
        label: {
          position: 'top',
          verticalAlign: 'middle',
          align: 'center',
          fontSize: 14,

        },
        leaves: {
          label: {
            position: 'bottom',
            verticalAlign: 'middle',
            align: 'center',
          },
        },
        emphasis: {
          focus: 'descendant',
        },
        expandAndCollapse: true,

        // 仅在 tooltip 或定制渲染中展示。
      },
    ],
  };
  myChart.setOption(option);
};
//数据加载
const fetchDataAndRender = async () => {
  loading.value = true;
  hasData.value = false;
  try {
    loadingText.value = "正在查找家谱的根人物...";
    const roots = await getRootsApi(props.treeId); //

    if (!roots || roots.length === 0) {
      emptyText.value = "此家谱没有根人物，请先在成员列表中添加成员并建立'父亲'或'母亲'关系。";
      if(myChart) myChart.clear();
      return;
    }

    // 默认使用第一个根人物来构建完整的树
    const rootPersonId = roots[0].personId; //
    loadingText.value = `正在以 [${roots[0].name}] 为根，构建完整的家谱树...`; //
    const chartData = await getFullTreeApi(rootPersonId); //

    if (chartData) {
      hasData.value = true;
      await nextTick();
      initChart(chartData);
    } else {
      emptyText.value = "无法构建家谱树数据。";
      if(myChart) myChart.clear();
    }
  } catch (e: any) {
    console.error("加载图表数据失败", e);
    emptyText.value = `加载图表失败: ${e.message}`;
    ElMessage.error("加载图表数据失败");
  } finally {
    loading.value = false;
  }
};

const refreshChart = () => {
  fetchDataAndRender();
};
defineExpose({ refreshChart });

onMounted(fetchDataAndRender);

// 监听treeId变化，如果变化了就重新加载
watch(() => props.treeId, () => {
    fetchDataAndRender();
});


</script>
